import streamlit as st
from auth import get_current_user, is_logged_in, logout
from database import get_conversations, add_conversation, delete_conversation
from datetime import datetime, timedelta

# 按时间分类对话
def categorize_conversations(conversations):
    today = datetime.now()
    categories = {
        "今天": [],
        "7天内": [],
        "30天内": [],
        "更早": [],
    }

    for conv in conversations:
        updated_at = datetime.strptime(conv[3], "%Y-%m-%d %H:%M:%S")
        delta = today - updated_at
        if delta.days == 0:
            categories["今天"].append(conv)
        elif delta.days <= 7:
            categories["7天内"].append(conv)
        elif delta.days <= 30:
            categories["30天内"].append(conv)
        else:
            categories["更早"].append(conv)

    return categories

# 截断字符串函数
def truncate_string(s, length=10):
    """Truncates the string to a specified length and adds an ellipsis if truncated."""
    return (s[:length] + '...') if len(s) > length else s

# 渲染二级导航
def render_secondary_navigation():
    # 检查用户是否登录
    if is_logged_in():
        user = get_current_user()

        # 二级导航内容
        st.markdown("### 导航")

        # 开启新对话按钮
        if st.button("开启新对话", key="new_conversation"):
            new_conversation_name = f"对话 {len(get_conversations(user['id'])) + 1}"
            conversation_id = add_conversation(user["id"], new_conversation_name)
            st.session_state.selected_conversation = conversation_id
            st.rerun()

        # 加载当前用户的历史对话
        conversations = get_conversations(user["id"])
        categorized_conversations = categorize_conversations(conversations)

        # 显示分类后的对话
        for category, convs in categorized_conversations.items():
            if convs:
                st.markdown(f"**{category}**")
                for conv in convs:
                    # 使用 Streamlit 组件来显示对话名称和操作按钮
                    # st.write(f"{conv[1]}")  # 显示对话名称
                    # 截断对话名称为10个字符
                    truncated_name = truncate_string(conv[1])
                    
                    # 创建一个容器来保持视觉上的连贯性，并使两个按钮在同一行显示
                    with st.container():
                        selected_button_key = f"select_{conv[0]}"
                        delete_button_key = f"delete_{conv[0]}"

                        col1, col2 = st.columns([1, 1])  # 在容器内创建两列以确保按钮并排
                        with col1:
                            if st.button(truncated_name, help=f"{conv[1]}", key=selected_button_key):
                                st.session_state.selected_conversation = conv[0]
                                st.rerun()
                        with col2:
                            if st.button("❌", help="删除会话", key=delete_button_key):
                                delete_conversation(conv[0])  # 删除对话
                                st.success(f"已删除对话: {conv[1]}")
                                st.rerun()  # 刷新页面

                    # 添加一点空间以区分不同的对话项
                    st.markdown("<br>", unsafe_allow_html=True)

        # 返回选中的对话 ID
        return st.session_state.get("selected_conversation", None)